package com.demo.common.controller;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo.enums.ResponseStatus;
import com.demo.exception.LoginException;
import com.demo.util.DateUtils;
import com.demo.util.JwtUtil;
import com.demo.web.vo.LoginUser;
import com.demo.web.vo.SsoToken;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;

@Api("SSO")
@RestController
@RequestMapping("sso")
public class LoginController {

    @PostMapping("login")
    public SsoToken login(@RequestBody LoginUser login) {
        SsoToken token = new SsoToken();
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", login.getUsername());
        if (!"admin".equals(login.getUsername())) {
            throw new LoginException(ResponseStatus.LOGIN_ERROR);
        }
        LocalDateTime now = LocalDateTime.now();
        Date exp = DateUtils.toDate(now.plusSeconds(20));

        token.setToken(JwtUtil.createToken(claims, exp));
        exp = DateUtils.toDate(now.plusSeconds(60));
        token.setRefreshToken(JwtUtil.createToken(claims, exp));
        return token;
    }

    @PostMapping("refresh")
    public SsoToken refreshToken(@RequestParam("refreshToken") String refreshToken) throws Exception {
        Claims claims = JwtUtil.parseToken(refreshToken);
    

        if (claims == null) {
            throw new LoginException(ResponseStatus.REFRESH_TOKEN_EXPIRED);
        }

        Thread.sleep(5000L);
        SsoToken token = new SsoToken();
        Map<String, Object> claimsnew = new HashMap<>();
        claims.put("username", JwtUtil.getValue(claims, "username"));
        LocalDateTime now = LocalDateTime.now();
        Date exp = DateUtils.toDate(now.plusSeconds(20));

        token.setToken(JwtUtil.createToken(claimsnew, exp));
        exp = DateUtils.toDate(now.plusSeconds(60));
        token.setRefreshToken(JwtUtil.createToken(claimsnew, exp));
        return token;
    }

}
